package com.xiaohei.rabbitmq.one;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description: 消费者：接受信息
 * @Author: 王希辰
 * @Date: 2022/3/15 15:25
 */
public class Consumer {
    public static final String QUEUE_NAME="hello";
    //接收消息
    public static void main(String[] args) {
        //创建连接工厂
        ConnectionFactory factory=new com.rabbitmq.client.ConnectionFactory();
        factory.setHost("192.168.80.44");
        factory.setUsername("admin");
        factory.setPassword("admin");
        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            //声明 接收消息
            DeliverCallback deliverCallback=(consumerTag,message)->{
                System.out.println(new String(message.getBody()));
            };
            //取消消息时的回调
            CancelCallback cancelCallback=consumerTag -> {
                System.out.println("消费消息被中断");
            };
            /**
             * 接收消息
             * 1.消费那个队列
             * 2.消费成功之后是否要自动应答 false表示手动应答
             * 3.消费者未成功消费的回调
             * 4.消费者取消消费的回调
             */

            channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback);

        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
